package service.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import service.StoreAndAdminManager;
import util.DataUtil;
import vo.Store;

import com.foodshop.admin.jms.AdminJMS;

import dao.AdminDao;

@Service("sam")
public class StoreAndAdminManagerImpl implements StoreAndAdminManager{
	
	@Autowired(required=true)
	private AdminDao adminDao;
	
	
	@Override
	public boolean findStoreInfo(HttpServletResponse response,AdminJMS adminJMS) {
		
		List<Store> storeList = adminDao.findStoreInfo();
		if (storeList == null) {
			return false;
		}
		List<Store> storeFail = new ArrayList<>();
		List<Store> storeSuc = new ArrayList<>();
		for (Store store : storeList) {
			if (store.getStatus() == DataUtil.STORE_STATUS_SUCCESS) {
				storeSuc.add(store);
			}else {
				storeFail.add(store);
			}
		}
		List<Store> storeSort = storeSuc;
		
		Collections.sort(storeSort, new Comparator<Store>() {

			@Override
			public int compare(Store store1, Store store2) {
				
				int cn = store1.getComplainNum() - store2.getComplainNum();
				if (cn != 0) {
					return cn;
				}else {
					return store1.getStoreId() - store2.getStoreId();
				}
			}
		});
		JSONArray storeSortInfo = JSONArray.fromObject(storeSort);
		JSONArray storeSucInfo = JSONArray.fromObject(storeSuc);
		JSONArray storeFailInfo = JSONArray.fromObject(storeFail);
		List<JSONArray> store = new ArrayList<>();
		store.add(storeSortInfo);
		store.add(storeSucInfo);
		store.add(storeFailInfo);
		JSONArray storeJSON = JSONArray.fromObject(store);
		
		try {
			PrintWriter out = response.getWriter();
			out.write(storeJSON.toString());
			System.out.println("this is store Json : " + storeJSON.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
		
	}
}
